package cn.szzsi.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.kit.HttpKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

/**
 * Created by yuanzheng on 2016/12/17.
 */
public class WeixinUtil {
    private static final Log logger = Log.getLog(WeixinUtil.class);
    private static String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";


    public static String getAccessToken(String appid, String secret){
        String accseeUrl="https://api.weixin.qq.com/cgi-bin/token";
        String accessResult=HttpExtKit.sendGet(accseeUrl,"grant_type=client_credential&appid="+appid+"&secret="+secret+"");
        JSONObject obj=new JSONObject(accessResult);
        String access_token=obj.get("access_token").toString();
        return access_token;
    }

    public static final boolean sendNewsMsg(String openId, String message) {
//        String jsonStr = "{\"touser\":\"" + openId + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + message + "\"}}";
//        String str = "<xml>"+
//        "<ToUserName><![CDATA["+openId+"]]></ToUserName>"+
//        "<FromUserName><![CDATA[fromUser]]></FromUserName>"+
//        "<CreateTime>"+System.currentTimeMillis()+"</CreateTime>"+
//        "<MsgType><![CDATA[news]]></MsgType>"+
//        "<ArticleCount>1</ArticleCount>"+
//        "<Articles>"+
//        "<item>"+
//        "<Title><![CDATA[1]]></Title>"+
//        "<Description><![CDATA[2]]></Description>"+
//        "<PicUrl><![CDATA[3]]></PicUrl>"+
//        "<Url><![CDATA[4]]></Url>"+
//        "</item>"+
//        "</Articles>"+
//        "</xml>";
        String str = "<xml>"+
        "<ToUserName><![CDATA["+openId+"]]></ToUserName>"+
        "<FromUserName><![CDATA[fromUser]]></FromUserName>"+
        "<CreateTime>"+ System.currentTimeMillis()+"</CreateTime>"+
        "<MsgType><![CDATA[news]]></MsgType>"+
        "<ArticleCount>1</ArticleCount>"+
        "<Articles>"+
        "<item>"+
        "<Title><![CDATA[1]]></Title>"+
        "<Description><![CDATA[2]]></Description>"+
        "<PicUrl><![CDATA[3]]></PicUrl>"+
        "<Url><![CDATA[4]]></Url>"+
        "</item>"+
        "</Articles>"+
        "</xml>";
        boolean isSuccess = true;
        String jsonResult = HttpKit.post(sendUrl + AccessTokenApi.getAccessToken().getAccessToken(), str);
        try {
            Map map = new ObjectMapper().readValue(jsonResult, Map.class);
            int errcode = Integer.parseInt(map.get("errcode").toString());
            if (errcode == 40001){
                AccessTokenApi.refreshAccessToken();
                isSuccess = sendMsg(openId,message);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("send:\n" + str);
                logger.debug("\nrecive:\n" + jsonResult);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    public static final boolean sendMsg(String openId, String message) {
        String jsonStr = "{\"touser\":\"" + openId + "\",\"msgtype\":\"news\",\"text\":{\"content\":\"" + message + "\"}}";
        boolean isSuccess = true;
        String jsonResult = HttpKit.post(sendUrl + AccessTokenApi.getAccessToken().getAccessToken(), jsonStr);
        try {
            Map map = new ObjectMapper().readValue(jsonResult, Map.class);
            int errcode = Integer.parseInt(map.get("errcode").toString());
            if (errcode == 40001){
                AccessTokenApi.refreshAccessToken();
                isSuccess = sendMsg(openId,message);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("send:\n" + jsonStr);
                logger.debug("\nrecive:\n" + jsonResult);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }
}
